
package com.jf.cloud.multishop.service.impl;

import com.jf.cloud.api.multishop.constant.ShopStatus;
import com.jf.cloud.api.multishop.vo.ShopDetailVO;
import com.jf.cloud.common.exception.LuckException;
import com.jf.cloud.common.security.AuthUserContext;
import com.jf.cloud.multishop.constant.AuditStatus;
import com.jf.cloud.multishop.mapper.ShopAuditingMapper;
import com.jf.cloud.multishop.mapper.ShopCompanyMapper;
import com.jf.cloud.multishop.mapper.ShopDetailMapper;
import com.jf.cloud.multishop.model.ShopAuditing;
import com.jf.cloud.multishop.service.ShopApplyService;
import com.jf.cloud.multishop.vo.ShopAuditingVO;
import com.jf.cloud.multishop.vo.ShopCompanyVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.Objects;

/**
 * @author zz
 * @date 2021/4/29 17:23
 */
@Service
public class ShopApplyServiceImpl implements ShopApplyService {

    @Autowired
    private ShopAuditingMapper shopAuditingMapper;

    @Autowired
    private ShopDetailMapper shopDetailMapper;

    @Autowired
    private ShopCompanyMapper shopCompanyMapper;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void apply(Long shopId) {
        Date now = new Date();
        this.checkApplyInfo(shopId);
        // 插入一条开店申请审核记录
        ShopAuditingVO byshopId = shopAuditingMapper.getByshopId(shopId);
        ShopAuditing shopAuditing = new ShopAuditing();
        shopAuditing.setShopId(shopId);
        shopAuditing.setUserId(AuthUserContext.get().getUserId());
        shopAuditing.setStatus(AuditStatus.WAITAUDIT.value());
        shopAuditing.setUpdateTime(now);
        if (Objects.nonNull(byshopId)) {
            shopAuditing.setShopAuditingId(byshopId.getShopAuditingId());
            shopAuditingMapper.update(shopAuditing);
        } else {
            shopAuditing.setCreateTime(now);
            shopAuditingMapper.save(shopAuditing);
        }
        // 更新店铺状态为待审核
        shopDetailMapper.changeShopStatus(shopId, ShopStatus.OPEN_AWAIT_AUDIT.value());
    }

    private void checkApplyInfo(Long shopId) {
        ShopDetailVO shopDetailVO = shopDetailMapper.getByShopId(shopId);
        if (Objects.nonNull(shopDetailVO) && Objects.equals(shopDetailVO.getShopStatus(), ShopStatus.OPEN_AWAIT_AUDIT.value())) {
            throw new LuckException("店铺审核中，请不要重复提交");
        }
        ShopCompanyVO shopCompanyVO = shopCompanyMapper.getShopCompanyByShopIdAndStatus(shopId, AuditStatus.WAITAUDIT.value());
        if (Objects.isNull(shopCompanyVO)) {
            throw new LuckException("店铺工商信息未填写");
        }
    }

}
